package org.example.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
public class JwtUtil {
	
	private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);
	
	private static final String SECRET = "tvnnIVvf0SM0cs0uJbAc";

	/**
	 * 有效期 10days
	 */
     private static final long EXPIRATION_TIME  = 10 * 24 * 60 * 60 * 1000;

    /**
     * HS256加密
     * @return
     * @throws Exception
     */
    public static String createTokenHs256(Map<String,String> subject) {
    	String token="";
    	try {
    		long nowMillis = System.currentTimeMillis();
    		long expMillis = nowMillis + EXPIRATION_TIME;
    		Date exp = new Date(expMillis);
    		
    	    Algorithm algorithm = Algorithm.HMAC256(SECRET);
    	    token = JWT.create()
				//设置主题
    	    	.withSubject("login")
				//设置谁生成的签名
    	        .withIssuer("clq")
				.withClaim("userId", subject.get("userId"))
				.withClaim("companyId", subject.get("companyId"))
				.withClaim("mobile", subject.get("mobile"))
				//设置过期时间
    	        .withExpiresAt(exp)
				//签名Signature
    	        .sign(algorithm);
    	} catch (JWTCreationException exception){
    		logger.error("HS256加密异常",exception.getMessage());
    	}
		return token;
	}
    
    /**
     * HS256解密
     * @param token
     * @throws Exception
     */
    public static Map<String,String> verifyTokenHs256(String token){
		Map<String,String> map = new HashMap<String,String>(ValidationUtil.getHashMapValue(3));
    	try {
    	    Algorithm algorithm = Algorithm.HMAC256(SECRET);
    	    JWTVerifier verifier = JWT.require(algorithm)
    	        .withIssuer("clq")
    	        .build();
			DecodedJWT jwt = verifier.verify(token);
			Map<String, Claim> claimMap = jwt.getClaims();

			String userId = claimMap.get("userId").asString();
			String companyId = claimMap.get("companyId").asString();
			String mobile = claimMap.get("mobile").asString();
			map.put("userId",userId);
			map.put("companyId",companyId);
			map.put("mobile",mobile);

    	} catch (JWTVerificationException exception){
    		logger.error("HS256解密异常",exception.getMessage());
    		return null;
    	}
    	return map;
	}
    
    public static void main(String[] args) {
		try {
			Map<String,String> subject = new HashMap<>(ValidationUtil.getHashMapValue(3));
			subject.put("userId","123");
			subject.put("companyId","1234");
			subject.put("mobile","18122217992");

			String in = createTokenHs256(subject);
			System.out.println(in);

			Map<String,String> map = verifyTokenHs256(in);
			System.out.println(map.get("userId")+"=="+map.get("companyId")+"==="+map.get("mobile"));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
